<template>
  <div class="app-container">
    <!--    查询对话框-->
    <el-dialog
      :title="title"
      v-model="openSearch"
      :close-on-click-modal="false"
      draggable
      width="440px"
      append-to-body
    >
      <el-form
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        v-show="showSearch"
        label-width="68px"
        style="margin-left: 55px"
      >
        <el-col :span="24">
          <el-form-item label="变更单号" prop="bgDjbh">
            <el-input
              v-model="queryParams.bgDjbh"
              placeholder="请输入变更单号"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="状态标志" prop="bgZtbz">
            <el-select
              v-model="queryParams.bgZtbz"
              placeholder="请选择状态标志"
              clearable
              size="small"
            >
              <el-option
                v-for="dict in bgZtbzOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="创建时间" prop="createTime">
            <el-date-picker
              clearable
              size="small"
              v-model="queryParams.createTime"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择创建时间"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item
            style="margin-top: 25px; display: flex; justify-content: flex-end"
          >
            <el-button @click="cancel">取消</el-button>
            <el-button type="primary" @click="handleQuery">确认</el-button>
          </el-form-item>
        </el-col>
      </el-form>
    </el-dialog>
    <el-row :gutter="10" class="mb8">
      <el-col :span="18" style="display: flex; align-items: flex-start">
        <el-button
          type="primary"
          plain
          icon="el-icon-search"
          size="mini"
          @click="handleSearchs"
          >搜索</el-button
        >
        <el-button
          type="primary"
          plain
          icon="el-icon-check"
          size="mini"
          :disabled="single"
          @click="handleSubmit"
          v-hasPermi="['project:bgs:check']"
        >
          审核
        </el-button>
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleCancellation"
          v-hasPermi="['project:bgs:rollback']"
        >
          撤回
        </el-button>
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['project:bg:export']"
        >
          导出
        </el-button>
        <Tag type="dot" color="#bb0331">审核</Tag>
      </el-col>
      <el-col :span="6" style="text-align: right">
        <Page
          style="margin-right: 0px"
          :current="queryParams.pageNum"
          :page-size="queryParams.pageSize"
          :total="total"
          @on-change="pageChange"
          simple
        ></Page>
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>
    <split-pane
      :min-percent="10"
      :default-percent="50"
      split="horizontal"
      style="height: calc(100vh - 200px)"
    >
      <template #paneL>
        <el-table
          v-loading="loading"
          :data="bgList"
          border
          stripe
          :row-style="{ padding: '0px' }"
          :cell-style="iCellStyle"
          :header-row-style="{ padding: '2px' }"
          :header-cell-style="{ 'text-align': 'center', padding: '2px' }"
          highlight-current-row
          height="100%"
          ref="multipleTable"
          @selection-change="handleSelectionChange"
          @row-click="getChildList"
        >
          <el-table-column label="#" type="index" width="55" align="center" />
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column
            label="变更单号"
            width="150"
            align="center"
            prop="bgDjbh"
          />
          <el-table-column label="ECN单号" align="center" prop="bgEcnno" />
          <el-table-column
            label="备注"
            show-overflow-tooltip
            align="center"
            prop="remark"
          />
          <el-table-column
            label="作废理由"
            show-overflow-tooltip
            align="center"
            prop="bgNgdesc"
          />
          <el-table-column label="创建人员" align="center" prop="createBy" />
          <el-table-column
            label="创建时间"
            align="center"
            prop="createTime"
            width="150"
          >
            <template #default="scope">
              <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="更改人员"
            align="center"
            width="120"
            prop="updateBy"
          />
          <el-table-column
            label="更改时间"
            align="center"
            prop="updateTime"
            width="150"
          >
            <template #default="scope">
              <span>{{ parseTime(scope.row.updateTime, "{y}-{m}-{d}") }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="审核人员"
            align="center"
            width="120"
            prop="bgShry"
          />
          <el-table-column
            label="审核日期"
            align="center"
            prop="bgShrq"
            width="150"
          >
            <template #default="scope">
              <span>{{ parseTime(scope.row.bgShrq, "{y}-{m}-{d}") }}</span>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <template #paneR>
        <el-table
          border
          stripe
          :row-style="{ padding: '0px' }"
          :cell-style="{ padding: '0px' }"
          :header-row-style="{ padding: '2px' }"
          :header-cell-style="{ 'text-align': 'center', padding: '2px' }"
          highlight-current-row
          height="100%"
          v-loading="loading"
          :data="bgdList"
        >
          <el-table-column label="#" type="index" width="55" align="center" />
          <el-table-column
            label="变更类型"
            width="100"
            align="center"
            prop="bgdType"
          >
            <template #default="scope">
              <dict-tag :options="bgStyleOptions" :value="scope.row.bgdType" />
            </template>
          </el-table-column>
          <el-table-column
            label="父项代码"
            width="130"
            align="center"
            prop="bgdFxdm"
          />
          <el-table-column
            label="父项品名规格"
            show-overflow-tooltip
            width="300"
            prop="bgdFxdmPmgg"
          />
          <el-table-column
            label="子项代码"
            show-overflow-tooltip
            width="130"
            align="center"
            prop="bgdZxdm"
          />
          <el-table-column
            label="子项品名规格"
            show-overflow-tooltip
            width="300"
            prop="bgdZxdmPmgg"
          />
          <el-table-column
            label="替换代码"
            align="center"
            width="130"
            prop="bgdReplaceZxdm"
          />
          <el-table-column
            label="替换品名规格"
            width="200"
            align="center"
            prop="bgdReplaceZxdmPmgg"
          />
          <el-table-column
            label="采购属性"
            width="80"
            align="center"
            prop="bgdCgsx"
          >
            <template #default="scope">
              <dict-tag :options="bomCgsxOptions" :value="scope.row.bgdCgsx" />
            </template>
          </el-table-column>
          <el-table-column label="单位" width="80" align="center" prop="bgdDw">
            <template #default="scope">
              <dict-tag :options="itmDwOptions" :value="scope.row.bgdDw" />
            </template>
          </el-table-column>
          <el-table-column
            label="主成型标识"
            width="100"
            align="center"
            prop="bgdMain"
          >
            <template #default="scope">
              <dict-tag :options="bodWwbzOptions" :value="scope.row.bgdMain" />
            </template>
          </el-table-column>
          <el-table-column
            label="单位用量"
            width="80"
            align="center"
            prop="bgdDwyl"
          />
          <el-table-column
            label="备注"
            width="60"
            align="center"
            prop="remark"
          />
          <el-table-column
            label="创建时间"
            align="center"
            prop="createTime"
            width="100"
          >
            <template #default="scope">
              <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="创建人员"
            width="80"
            align="center"
            prop="createBy"
          />
          <el-table-column
            label="操作"
            align="center"
            fixed="right"
            width="120"
            class-name="small-padding fixed-width"
          >
            <template #default="scope">
              <el-button
                v-if="bgdDjbh.bgZtbz === '1'"
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleDeleteBgd(scope.row)"
                v-hasPermi="['project:bg:remove']"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
    </split-pane>

    <!-- 撤回对话框 -->
    <el-dialog
      :title="title"
      v-model="cancellationView"
      :close-on-click-modal="false"
      draggable
      width="600px"
      append-to-body
    >
      <el-form
        ref="cancellationForm"
        :model="form"
        :rules="cancellationFormRules"
        label-width="100px"
      >
        <el-form-item label="撤回理由" prop="bgRollbackDesc">
          <el-input
            v-model="form.bgRollbackDesc"
            placeholder="请输入作废理由"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelCancellation">取 消</el-button>
        <el-button type="primary" @click="submitCancellationForm"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listBg,
  getBg,
  delBg,
  addBg,
  updateBg,
  exportBg,
  submitBg,
  cancellationBg,
  submitBgd,
  findBodDets,
  deleteBgd,
  cancelBg,
  submitBgs,
} from "@/api/project/bg";
import { getAllCgList, getAllCgListNormal } from "@/api/project/mstr";
import { selectItmByWldm } from "@/api/project/materiel";
import { getBomByOrders, JudgeParentWithChild } from "@/api/project/bom";

export default {
  name: "Bgs",
  data() {
    return {
      tableH: 1,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      //采购
      bomCgsxOptions: [],
      bodWwbzOptions: [],
      //有效采购属性
      bomCgsxOptionsNromal: [],
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // bom资料变更表格数据
      bgList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openSearch: false,

      //当前选中数据
      currentData: [],

      //单位
      itmDwOptions: [],

      //详情表
      bgdList: [],

      //保存当前订单
      bgdDjbh: null,

      //作废框
      cancellationView: false,

      bgdForm: {},

      //选中的变更单号
      bgDjbhs: [],

      //添加变更弹窗
      change: false,
      // 状态标志字典
      bgZtbzOptions: [],

      //类型字典
      bgStyleOptions: [],

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        bgDjbh: null,
        bgZtbz: "1",
        createTime: null,
        bgTjflag: "1",
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      bgdRules: {
        bgdFxdm: [
          { required: true, message: "父项代码不能为空", trigger: "blur" },
        ],
        bgdZxdm: [
          { required: true, message: "子项代码不能为空", trigger: "blur" },
        ],
        bgdDwyl: [
          { required: true, message: "单位用量不能为空", trigger: "blur" },
        ],
        bgdCgsx: [
          { required: true, message: "采购属性不能为空", trigger: "change" },
        ],
      },
      cancellationFormRules: {
        bgNgdesc: [
          { required: true, message: "作废理由不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getDicts("sys_flag").then((response) => {
      this.bodWwbzOptions = response.data;
    });
    this.getList();
    this.getDicts("sys_bom_bg_ztbz").then((response) => {
      this.bgZtbzOptions = response.data;

      //去除作废
      this.bgZtbzOptions.pop();
    });
    this.getDicts("sys_unit").then((response) => {
      this.itmDwOptions = response.data;
    });
    this.getDicts("sys_bom_bg_style").then((response) => {
      this.bgStyleOptions = response.data;
    });
    getAllCgList().then((response) => {
      this.bomCgsxOptions = response.data;
      for (let i of this.bomCgsxOptions) {
        i.dictLabel = i.cgName;
        i.dictValue = i.cgId + "";
        i.listClass = "default";
      }
    });
  },
  methods: {
    iCellStyle({ row, column, rowIndex, columnIndex }) {
      //通过状态
      if (row.bgTjflag == "1" && row.bgZtbz == 2) {
        return "color:#bb0331";
      }
      //作废状态
      else if (row.bgZtbz == 3) {
        return "color:#a8ace0";
      }
    },

    /** 查询bom资料变更列表 */
    getList(row) {
      this.loading = true;
      this.tableH = (document.body.clientHeight - 188) / 2;
      this.queryParams.pageSize = this.tableH > 350 ? 15 : 10;
      listBg(this.queryParams).then((response) => {
        this.bgList = response.rows;
        this.total = response.total;

        this.loading = false;
        this.bgdList = [];
        if (row) {
          this.getChildList(row);
        } else {
          if (this.bgList != null && this.bgList.length > 0) {
            this.getChildList(this.bgList[0]);
          }
        }
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.openSearch = false;
    },
    cancelCancellation() {
      this.cancellationView = false;
      this.reset();
    },
    cancelBgdForm() {
      this.change = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        bgId: null,
        bgDjbh: null,
        bgEcnno: null,
        bgZtbz: null,
        bgTjflag: null,
        remark: null,
        bgNgdesc: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        bgShry: null,
        bgShrq: null,
        bgRollbackDesc: null,
      };
      this.bgdForm = {
        bgdId: null,
        bgdDjbh: null,
        bgdType: "add",
        bgdFxdm: null,
        bgdZxdm: null,
        bgdDwyl: null,
        bgdCgsx: null,
        remark: null,
        createBy: null,
        createTime: null,
        bgdEcnno: null,
        bgdReplaceZxdm: null,
        bgdFxdmPmgg: null,
        bgdZxdmPmgg: null,
        bgdReplaceZxdmPmgg: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
      this.openSearch = false;
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.currentData = selection;
      this.ids = selection.map((item) => item.bgId);
      this.bgDjbhs = selection.map((item) => item.bgDjbh);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加bom资料变更";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const bgId = row.bgId || this.ids;
      getBg(bgId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改bom资料变更";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.bgId != null) {
            updateBg(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBg(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const bgIds = row.bgId || this.ids;
      this.$confirm(
        '是否确认删除bom资料变更编号为"' + bgIds + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return delBg(bgIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有bom资料变更数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.exportLoading = true;
          return exportBg(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
          this.exportLoading = false;
        })
        .catch(() => {});
    },
    handleSearchs() {
      this.reset();
      this.title = "查询bom资料维护";
      this.openSearch = true;
    },
    /*提交审核*/
    handleSubmit() {
      //作废的单据不可以再审核
      for (let i of this.currentData) {
        if (i.bgZtbz == 3) {
          this.msgError(i.bgDjbh + "单据已经作废，禁止审核");

          return;
        }
        if (i.bgZtbz == 2) {
          this.msgError(i.bgDjbh + "单据已经审核，禁止重复审核");

          return;
        }
      }

      //审核只允许审核一个
      const bgDjbhs = this.bgDjbhs;
      this.$confirm("是否确认审核,一旦审核不可撤回?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return submitBgs(bgDjbhs);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("提交成功");
        })
        .catch(() => {});
    },
    /*撤回*/
    handleCancellation() {
      //已经审核的单据不能撤回
      for (let i of this.currentData) {
        if (i.bgZtbz == 2) {
          this.msgError(i.bgDjbh + "已经审核，禁止撤回");

          return;
        }
      }
      this.$confirm("是否确认撤回单据?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {})
        .then(() => {
          this.cancellationView = true;
          this.title = "请填写撤回理由";
        })
        .catch(() => {});
    },
    pageChange(page) {
      this.queryParams.pageNum = page;
      this.getList();
    },
    submitCancellationForm() {
      this.$refs["cancellationForm"].validate((valid) => {
        if (valid) {
          cancelBg(this.ids, this.form.bgRollbackDesc).then((response) => {
            this.msgSuccess("撤回成功");
            this.cancellationView = false;
            this.getList();
          });
        }
      });
    },

    //查询子项
    getChildList(row) {
      //点击行触发，选中或不选中复选框
      this.$refs.multipleTable.clearSelection();
      this.$refs.multipleTable.toggleRowSelection(row);
      this.bgdDjbh = row;

      if (row.bgDjbh != null) {
        findBodDets(row.bgDjbh).then((response) => {
          this.bgdList = response.data;
        });
      }
    },

    //删除子项
    handleDeleteBgd(row) {
      const bgdIds = row.bgdId;
      this.$confirm("是否确认删除该数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return deleteBgd(bgdIds);
        })
        .then(() => {
          this.getList(this.bgdDjbh);
          this.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
  },
};
</script>
